/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-12-14 18:27:22
 * @LastEditTime: 2025-02-26 20:50:46
 * @FilePath: /monitor_belt/src/views/setting/plc_config/index.tsx
 */
import {
  remoteComInfo,
  remoteControllerInfo,
  saveControllerInfo,
  updateComInfo,
} from "@/api/system";
import { useStore } from "@/store/conveyor";
import {
  Button,
  Card,
  Col,
  Divider,
  Flex,
  Form,
  Input,
  InputNumber,
  message,
  Row,
  Select,
  Spin,
} from "antd";
import { useEffect, useState } from "react";
import { CloseOutlined } from "@ant-design/icons";
import { controllerTypeList } from "./dictionary";

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const PlcConfig = () => {
  const [form] = Form.useForm();
  const basic = {
    type: undefined,
    conveyor_id: undefined,
    ip: "",
    port: "",
    timeout: 30,
    heart: "",
    conveyor_state_addr: "",
    tear_alarm_addr: "",
    motor_speed_addr: "",
    temp_addr: "",
  };
  const { conveyorList } = useStore();
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    searchInfo();
  }, []);

  const searchInfo = async () => {
    setLoading(true);
    try {
      let res = await remoteControllerInfo();
      let { data } = res;
      if (data?.length) {
        data.map((item) => {
          if (item?.dcs_ip) {
            item.ip = item.dcs_ip;
            item.port = item.dcs_port;
          } else if(item?.plc_ip) {
            item.ip = item.plc_ip;
            item.port = item.plc_port;
          }
        });
        form.setFieldValue("items", [...data]);
      }
    } finally {
      setLoading(false);
    }
  };

  const onFinish = () => {
    form
      .validateFields()
      .then(async (values) => {
        setLoading(true);
        try {
          console.log(values);
          let items = [...values.items];
          items.map((item) => {
            let findConveyor = conveyorList.find(
              (con) => con.id == item.conveyor_id
            );
            item.device = findConveyor.conveyor;
            if (item.type == "dcs") {
              item.dcs_ip = item.ip;
              item.dcs_port = item.port;
            } else {
              item.plc_ip = item.ip;
              item.plc_port = item.port;
            }
          });
          await saveControllerInfo(items);
          message.success("操作成功");
        } finally {
          setLoading(false);
        }
      })
      .catch((info) => {
        console.log("Validate Failed - ", info);
      });
  };

  const onReset = () => {
    form.resetFields();
  };
  return (
    <Flex flex={1} justify="center">
      <Form
        {...layout}
        form={form}
        name="basic"
        style={{ width: "1000px" }}
        onFinish={onFinish}
        initialValues={{ items: [{ ...basic }] }}
      >
        <Form.List name={"items"}>
          {(fields, { add, remove }) => (
            <Flex vertical gap={20}>
              {fields.map((field, index: number) => (
                <Card
                  size="small"
                  title={`控制器配置`}
                  key={field.key}
                  extra={
                    <CloseOutlined
                      onClick={() => {
                        remove(field.name);
                      }}
                    />
                  }
                >
                  <Row>
                    <Col span={12}>
                      <Form.Item
                        label="控制器类型"
                        name={[field.name, "type"]}
                        rules={[{ required: true }]}
                      >
                        <Select
                          allowClear
                          placeholder="请选择"
                          style={{ width: "100%" }}
                          options={[...controllerTypeList]}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="输送带"
                        name={[field.name, "conveyor_id"]}
                        rules={[{ required: true }]}
                      >
                        <Select
                          allowClear
                          placeholder="请选择运输线"
                          style={{ width: "100%" }}
                          fieldNames={{ label: "conveyor", value: "id" }}
                          options={[...conveyorList]}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="IP"
                        name={[field.name, "ip"]}
                        rules={[{ required: true }]}
                      >
                        <Input placeholder="请输入IP" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="端口"
                        name={[field.name, "port"]}
                        rules={[{ required: true }]}
                      >
                        <Input placeholder="请输入端口" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="超时时间"
                        name={[field.name, "timeout"]}
                        rules={[{ required: true }]}
                      >
                        <InputNumber
                          min={1}
                          precision={0}
                          style={{ width: "100%" }}
                          addonAfter="毫秒"
                          placeholder="请输入超时时间"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="心跳间隔"
                        name={[field.name, "heart"]}
                      >
                        <InputNumber
                          min={1}
                          precision={0}
                          style={{ width: "100%" }}
                          addonAfter="毫秒"
                          placeholder="请输入心跳间隔"
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="输送带状态地址"
                        name={[field.name, "conveyor_state_addr"]}
                        rules={[{ required: true }]}
                      >
                        <Input placeholder="请输入输送带状态地址" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="寄存器地址"
                        name={[field.name, "tear_alarm_addr"]}
                        rules={[{ required: true }]}
                      >
                        <Input placeholder="请输入寄存器地址" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="撕裂检测报警地址"
                        name={[field.name, "motor_speed_addr"]}
                        rules={[{ required: true }]}
                      >
                        <Input placeholder="请输入撕裂检测报警地址" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="温度检测地址"
                        name={[field.name, "temp_addr"]}
                        rules={[{ required: true }]}
                      >
                        <Input placeholder="请输入温度检测地址" />
                      </Form.Item>
                    </Col>
                  </Row>
                </Card>
              ))}
              <Button
                type="dashed"
                size="large"
                style={{ width: "240px", margin: "0 auto" }}
                onClick={() => add()}
                block
              >
                添加控制器配置
              </Button>
            </Flex>
          )}
        </Form.List>

        <Flex gap={30} justify="center" style={{ marginTop: "20px" }}>
          <Button htmlType="button" onClick={onReset}>
            重置
          </Button>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Flex>
      </Form>
      <Spin spinning={loading} fullscreen />
    </Flex>
  );
};

export default PlcConfig;
